package com.yuanxiao.common.api.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yuanxiao.common.api.constant.UsedType;
import com.yuanxiao.common.api.entity.dto.SysFeignCfgDTO;
import com.yuanxiao.common.api.feign.FeignCallbackAPI;
import com.yuanxiao.common.api.feign.SysServerFeignClient;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.yuanxiao.common.core.result.R;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author: cg
 * Date: 2022-10-22 15:05
 * Content:
 */
public class FeignBaseService {
    @Qualifier("sysServerFeignClient")
    @Autowired
    private SysServerFeignClient sysServerFeignClient;

    @Qualifier("feignCallbackAPI")
    @Autowired
    private FeignCallbackAPI feignCallbackAPI;

    /**
     * 配置化feign请求
     * @param serverCode 业务代号
     * @param usedType 使用场景（judge:controller判断；business：service 业务处理）
     * @param bizCode 具体代表某个业务/方法代号
     * @param bodyArgs body传参
     * @param pathArgs 路径参数 （如：/delete/{id}）
     * @return
     */
    public R feignCall(String serverCode, UsedType usedType, String bizCode, Object bodyArgs, Object pathArgs) {
        if (StringUtils.isBlank(serverCode) || StringUtils.isBlank(bizCode)){
            return R.returnSuccessWrapper();
        }
        JSONObject bodyMap = new JSONObject();
        Map<String,Object> queryMap = new HashMap<String,Object>();
        if (bodyArgs != null){
            bodyMap = new JSONObject(JSONUtil.toJsonStr(bodyArgs));
        }
        if (pathArgs != null){
            queryMap = BeanUtil.beanToMap(pathArgs);
        }
        if (StringUtils.isBlank(serverCode)){
            return R.error("serverCode is not empty");
        }
        if (usedType == null){
            return R.error("usedType is not empty");
        }
        //请求获取feign_cfg的配置
        R sysR =  sysServerFeignClient.handelFeignCallList(serverCode,usedType.getType(),bizCode);
        if (!sysR.getCode().equals("0")){
            return sysR;
        }
        List<SysFeignCfgDTO> list = JSONUtil.toList(JSONUtil.parseArray(sysR.getData()), SysFeignCfgDTO.class);
        R resultR = new R();
        URI host = null;
        String path;
        if (list.size() > 0){
            for (SysFeignCfgDTO cfg : list) {
                resultR.put("code","1");
                resultR.put("message","method is empty");
                try {
                    host = new URI(cfg.getHost());
                } catch (URISyntaxException e) {
                    e.printStackTrace();
                }
                path = cfg.getPath();
                if ("GET".equals(cfg.getRequestMode())){
                    resultR = feignCallbackAPI.getCallback(host,path,queryMap);

                }else if ("POST".equals(cfg.getRequestMode())){
                    resultR = feignCallbackAPI.postCallback(host,path,queryMap,bodyMap);

                }else if ("PUT".equals(cfg.getRequestMode())){
                    resultR = feignCallbackAPI.putCallback(host,path,queryMap,bodyMap);

                }else if ("DELETE".equals(cfg.getRequestMode())){
                    resultR = feignCallbackAPI.deleteCallback(host,path,queryMap,bodyMap);

                }
                if (!"0".equals(resultR.getCode())){
                    return resultR;
                }
            }
        }
        return R.returnSuccessWrapper().setData(resultR.getData());
    }

}
